package com.weh.booksystem.controller;


import com.weh.booksystem.entity.User;
import com.weh.booksystem.service.MailService;
import com.weh.booksystem.service.UserService;
import com.weh.booksystem.utils.EmailService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;



    //用户：个人信息
    @GetMapping(value = "/{id}")
    public User getUser(@PathVariable("id") int id){
        return userService.getUserById(id);
    }

    @GetMapping(value = "/{email}/{password}")
    public User getUserByEmailAndPassword(@PathVariable("email") String email, @PathVariable("password") String password){
        return userService.getUserByEmailAndPassword(email, password);
    }

    //管理员：查询读者信息
    @GetMapping(value = "/email/{email}")
    public User getUserByEmail(@PathVariable("email") String email){
        return userService.getUserByEmail(email);
    }

    //修改个人信息
    @PutMapping(value = "/information/{id}")
    public void modifyUserInformation(@PathVariable("id") int id, @RequestParam String name, @RequestParam String sex, @RequestParam int age, @RequestParam String telephone, @RequestParam String speciality){
        userService.modifyUserInformation(id, name, sex, age, telephone, speciality);
    }

    @PostMapping(value = "/login")
    public Map<String, Object> login(@RequestParam String email, @RequestParam String password, HttpServletRequest httpRequest){
        int uid = userService.getUserId(email, password);
        HttpSession session = httpRequest.getSession();
        session.setAttribute("uid",uid);
        System.out.println("uid = " + uid);
        return userService.login(email, password);
    }

//    @PostMapping(value = "/login")
//    public Map<String, Object> login(@RequestParam String email, @RequestParam String password, HttpServletRequest httpRequest) {
//        Map<String, Object> map = new HashMap<>();
//
//        // 在这里进行登录验证
//        User users = userService.getUserByEmailAndPassword(email, password);
//        System.out.println("users = " + users.toString());
//
//        if (users != null){
//            map.put("status", true);
//            map.put("userId", users.getId());
//            map.put("ifBanned", users.isIfBanned());
//
//            // 将userId存入Session
//            HttpSession session = httpRequest.getSession();
//            session.setAttribute("userId", users.getId());
//        } else {
//            map.put("status", false);
//        }
//        return map;
//    }

    //检查邮箱正确与否
    @PostMapping(value = "/register")
    public Map<String, Object> checkEmail(@RequestParam String email) throws MessagingException {
        Map<String, Object> map = new HashMap<>(3);
        if (userService.getUserByEmail(email) != null){
            map.put("status", false);
            return map;
        }
        else{
            String checkCode = mailService.sendCheckCode(email);
            map.put("status", true);
            map.put("checkcode", checkCode);
            return map;
        }
    }

    //注册保存用户
    @PostMapping
    public boolean addUser(@RequestParam String email, @RequestParam String password){
        userService.addUser(email, password, false);
        return true;
    }

    //删除用户
    @DeleteMapping(value = "/{id}")
    public void deleteUser(@PathVariable("id") int id){
        userService.deleteUser(id);
    }

    //封禁解封账户
    @PutMapping(value = "/{id}")
    public boolean banUser(@PathVariable("id") int id){
        userService.banUser(id);
        return true;
    }


    //管理员超期邮件提醒
    @PostMapping(value = "/email")
    public boolean sendOverDueMail(@RequestParam String email, @RequestParam String bookName) throws MessagingException {
        mailService.sendOverDueMail(email, bookName);
        return true;
    }

    //用户修改密码
    @PutMapping(value = "/password/{id}")
    public boolean modifyPassword(@PathVariable("id") int id, @RequestParam String oldPassword, @RequestParam String newPassword){
        return userService.modifyPassword(id, oldPassword, newPassword);
    }

    @PostMapping("/logout")
    public ResponseEntity<String> logout(HttpServletRequest request, SessionStatus sessionStatus) {
        HttpSession session = request.getSession(false);
        System.out.println("session = " + session);
        if (session != null) {
            session.invalidate();
        }
        sessionStatus.setComplete();
        System.out.println("session = " + session);
        return ResponseEntity.ok("注销成功");
    }
}
